/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.icybear.gae.pechapaii.service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

/**
 *
 * @author Bearice
 */
public class TwitterService {

    private CryptoService cryptoService;
    public TwitterFactory twitterFactory = new TwitterFactory();

    public Twitter createTwitter(HttpServletRequest req) {
        HttpSession sess = req.getSession();
        if (sess.getAttribute("user") == null) {
            String user = null, pass = null;
            try {
                for (Cookie cookie : req.getCookies()) {
                    if (cookie.getName().equals("user")) {
                        user = cryptoService.decrypt(cookie.getValue());
                    }
                    if (cookie.getName().equals("pass")) {
                        pass = cryptoService.decrypt(cookie.getValue());
                    }
                }
            } catch (Exception e) {
                return null;
            }
            if (user != null && pass != null) {
                Twitter twitter = twitterFactory.getInstance(user, pass);
                try {
                    twitter.verifyCredentials();
                } catch (TwitterException ex) {
                    return null;
                }
                sess.setAttribute("user", user);
                sess.setAttribute("pass", pass);
                return twitter;
            }
            return null;
        }
        return twitterFactory.getInstance((String) sess.getAttribute("user"), (String) sess.getAttribute("pass"));
    }

    public CryptoService getCryptoService() {
        return cryptoService;
    }

    public void setCryptoService(CryptoService cryptoService) {
        this.cryptoService = cryptoService;
    }
}
